// pages/goods_list/index.js
import {request} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
      tabs:[
        {
          id:0,
          value:'综合',
          isActive:true
        },
        {
          id:1,
          value:'销量',
          isActive:false
        },
        {
          id:2,
          value:'价格',
          isActive:false
        },
      ],
      goodslist:[],
      pagenum:1,
  },
  QueryParams:{
    query:'',
    cid:'',
    pagenum:1,
    pagesize:10,
  },
  //总页数
  totalpagenum:1,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      // console.log(this.QueryParams);
      this.QueryParams.cid = options.cid;
      this.QueryParams.pagenum = this.data.pagenum;
      this.getGoodsList();
    
  },
  getGoodsList:function(){
    let that = this;
    request({
      url: 'https://api-hmugo-web.itheima.net/api/public/v1/goods/search',
      data:that.QueryParams,
    }).then(function(res){
      // console.log(res);
      //累积数组数据
      const oldgoodslist = that.data.goodslist.concat(res.data.message.goods);
      that.totalpagenum = Math.ceil(res.data.message.total / that.QueryParams.pagesize);
      // console.log(that.totalpagenum);
      that.setData({
        goodslist:oldgoodslist,
        pagenum:that.data.pagenum+1,
      })
      wx.stopPullDownRefresh();
    })
  },
  handleTabsItemChange:function(e){
      // console.log(e);
      const id = e.detail.id;
      const tabs = this.data.tabs.map(function(v){
          if(v.id == id){
             v.isActive=true;
          }else{
            v.isActive=false;
          }
           return v
      })
      this.setData({
        tabs
      })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log(this.data.pagenum,this.totalpagenum);
    if(this.data.pagenum > this.totalpagenum){
      wx.showToast({
        title: '没有下一页了',
        icon: 'none',
        duration: 2000
      })
    }else{
      this.QueryParams.pagenum = this.data.pagenum;
      this.getGoodsList();
    }
  },
  onPullDownRefresh:function(){
      this.totalpagenum=1;
      this.QueryParams.pagenum=1;
      this.setData({
        goodslist:[],
        pagenum:1
      })
      this.getGoodsList();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})